package com.unismc.charge.collector.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gitee.loyo.Request;
import com.gitee.loyo.Result;
import com.gitee.loyo.StationService;
import com.gitee.loyo.config.ChargeConst;
import com.gitee.loyo.config.ChargeNotifyProperties;
import com.gitee.loyo.config.ChargeProperties;
import com.gitee.loyo.data.*;
import com.gitee.loyo.post.QueryStationStatsPost;
import com.gitee.loyo.post.QueryStationStatusPost;
import com.gitee.loyo.post.QueryStationsPost;
import com.gitee.loyo.post.QueryTokenPost;
import com.gitee.loyo.result.QueryStationStatsResult;
import com.gitee.loyo.result.QueryStationStatusResult;
import com.gitee.loyo.result.QueryStationsResult;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("extra/bp/evcs/v1")
public class ChargingController implements StationService {
    @Resource
    RedisTemplate<String, Object> redisTemplate;
    @Resource
    ChargeNotifyProperties chargeNotifyProperties;
    @Resource
    ChargeProperties chargeProperties;
    @Resource
    ObjectMapper objectMapper;

    @PostMapping("/query_token")
    public Result<Token> queryToken(@RequestBody Request<QueryTokenPost> post) {
        QueryTokenPost data = post.getData();
        if(data == null || data.getOperatorId() == null
            || data.getOperatorSecret() == null){
            Result<Token> result = new Result<>(post);
            result.setRet(4004);
            result.setMsg("请求业务的参数不合法，各接口定义自己的必须参数");
            return result;
        }
        if(!chargeNotifyProperties.getOperatorId().equals(data.getOperatorId())){
            Result<Token> result = new Result<>(post);
            result.setRet(0);
            Token token = new Token();
            token.setOperatorId(chargeNotifyProperties.getOperatorId());
            token.setSuccStat(1);
            token.setFailReason(1);
            result.setData(token);
            return result;
        }
        if(!chargeNotifyProperties.getOperatorSecret().equals(data.getOperatorSecret())){
            Result<Token> result = new Result<>(post);
            result.setRet(0);
            Token token = new Token();
            token.setOperatorId(chargeNotifyProperties.getOperatorId());
            token.setSuccStat(1);
            token.setFailReason(2);
            result.setData(token);
            return result;
        }

        // 生成令牌
        Result<Token> result = new Result<>(post);
        result.setRet(0);
        Token token = new Token();
        token.setOperatorId(chargeNotifyProperties.getOperatorId());
        token.setAccessToken(UUID.randomUUID().toString());
        token.setTokenAvailableTime(24 * 3600);
        result.setData(token);
        // 保存到Redis
        redisTemplate.opsForValue().set(
            ChargeConst.REDIS_TCEC_OPS_TOKEN + chargeNotifyProperties.getOperatorId(),
            token,
            24 * 3600
        );
        log.info("OperatorID {} query token: {}", token.getOperatorId(), token.getAccessToken());
        return result;
    }

    @SneakyThrows
    @PostMapping("query_stations_info")
    @Override
    public Result<QueryStationsResult> queryStationsInfo(@RequestBody Request<QueryStationsPost> post) {
        log.info("check_charge_order: {}", objectMapper.writeValueAsString(post));
        QueryStationsPost postData = post.getData();
        log.info("查询充电信息参数：上次查询时间-{}, pageNo-{}，pageSize-{}",
                postData.getLastQueryTime(),
                postData.getPageNo(),
                postData.getPageSize());
        //生成测试数据
        QueryStationsResult postResult = new QueryStationsResult();
        postResult.setPageNo(postData.getPageNo());
        postResult.setItemSize(postData.getPageSize());
        postResult.setPageCount(postData.getPageNo() * postData.getPageSize());
        List<StationInfo> stationInfos = new ArrayList<>();
        postResult.setStationInfos(stationInfos);
        for (Integer i = 0; i < postData.getPageSize(); i++) {
            StationInfo stationInfo = new StationInfo();
            stationInfo.setStationId("11100011");
            stationInfo.setOperatorId("987654321");
            stationInfo.setEquipmentOwnerId("123456789");
            stationInfo.setStationName("站点1");
            stationInfo.setCountryCode("CN");
            stationInfo.setAreaCode("441781");
            stationInfo.setAddress("地址111");
            stationInfo.setStationTel("7925454");
            stationInfo.setServiceTel("187925454");
            stationInfo.setStationType(1);
            stationInfo.setStationStatus(50);
            stationInfo.setParkNums(3);
            stationInfo.setStationLng(110.11245);
            stationInfo.setStationLat(32.13324);
            stationInfo.setSiteGuide("向左100米");
            stationInfo.setConstruction(1);
            List<String> pictures = new ArrayList<>();
            pictures.add("http://example.img.com/test/1");
            pictures.add("http://example.img.com/test/2");
            stationInfo.setPictures(pictures);
            stationInfo.setMatchCars("私家车");
            stationInfo.setParkInfo("1楼");
            stationInfo.setBusineHours("24小时营业");
            stationInfo.setElectricityFee("15元/4小时，上限120元");
            stationInfo.setServiceFee("每次5元");
            stationInfo.setParkFee("每小时5元");
            stationInfo.setPayment("支持支付宝、微信、云闪付、现金");
            stationInfo.setSupportOrder(0);
            stationInfo.setRemark("其它描述");
            List<EquipmentInfo> equipmentInfos = new ArrayList<>();
            EquipmentInfo e1 = new EquipmentInfo();
            EquipmentInfo e2 = new EquipmentInfo();
            equipmentInfos.add(e1);
            equipmentInfos.add(e2);
            e1.setEquipmentId("10000000000003");
            e1.setManufacturerId("1234566777");
            e1.setManufacturerName("A级制造商");
            e1.setEquipmentModel("p3");
            e1.setProductionDate("2024-04-10");
            e1.setEquipmentType(3);
            ArrayList<ConnectorInfo> connectorInfos = new ArrayList<>();
            e1.setConnectorInfos(connectorInfos);
            ConnectorInfo info1 = new ConnectorInfo();
            ConnectorInfo info2 = new ConnectorInfo();
            connectorInfos.add(info1);
            connectorInfos.add(info2);
            info1.setConnectorId("1");
            info1.setConnectorName("接口1");
            info1.setConnectorType(1);
            info1.setVoltageUpperLimits(220);
            info1.setVoltageLowerLimits(220);
            info1.setCurrent(15);
            info1.setPower(3.3);
            info1.setParkNo("2");
            info1.setNationalStandard(1);
            e1.setEquipmentLng(23.123456);
            e1.setEquipmentLat(43.123456);
            e1.setPower(3.3);
            e1.setEquipmentName("一号充电桩");
            stationInfo.setEquipmentInfos(equipmentInfos);
            stationInfos.add(stationInfo);
        }

        Result<QueryStationsResult> result = new Result<>(post);
        result.setRet(0);
        result.setMsg("请求成功");
        result.setData(postResult);
        return result;
    }

    @SneakyThrows
    @PostMapping("query_station_status")
    @Override
    public Result<QueryStationStatusResult> queryStationStatus(@RequestBody Request<QueryStationStatusPost> post) {
        log.info("check_charge_order: {}", objectMapper.writeValueAsString(post));
        QueryStationStatusPost postData = post.getData();
        log.info("设备接口状态查询：查询充电站ID列表-{}", postData.getStationIds());
        //生成测试数据
        QueryStationStatusResult postResult = new QueryStationStatusResult();
        List<StationStatusInfo> stationStatusInfos = new ArrayList<>();
        postResult.setStationStatusInfos(stationStatusInfos);

        for (String stationId : postData.getStationIds()) {
            StationStatusInfo statusInfo = new StationStatusInfo();
            statusInfo.setStationId(stationId);
            ArrayList<ConnectorStatusInfo> connectorStatusInfos = new ArrayList<>();
            statusInfo.setConnectorStatusInfos(connectorStatusInfos);
            ConnectorStatusInfo connectorStatusInfo = new ConnectorStatusInfo();
            connectorStatusInfo.setConnectorId("1");
            connectorStatusInfo.setStatus(4);
            connectorStatusInfo.setLockStatus(0);
            connectorStatusInfo.setParkStatus(0);
            connectorStatusInfos.add(connectorStatusInfo);
            stationStatusInfos.add(statusInfo);
        }

        Result<QueryStationStatusResult> result = new Result<>(post);
        result.setRet(0);
        result.setMsg("请求成功");
        result.setData(postResult);
        return result;
    }

    @SneakyThrows
    @PostMapping("query_station_stats")
    @Override
    public Result<QueryStationStatsResult> queryStationStats(@RequestBody Request<QueryStationStatsPost> post) {
        log.info("check_charge_order: {}", objectMapper.writeValueAsString(post));
        QueryStationStatsPost postData = post.getData();
        log.info("查询统计信息：查询充电站ID-{}，统计开始时间-{}，统计结束时间-{}", postData.getStationId(), postData.getStartTime(), postData.getEndTime());
        QueryStationStatsResult postResult = new QueryStationStatsResult();
        StationStatsInfo statsInfo = new StationStatsInfo();
        postResult.setStationStats(statsInfo);

        statsInfo.setStationId(postData.getStationId());
        statsInfo.setStartTime(postData.getStartTime());
        statsInfo.setEndTime(postData.getEndTime());
        statsInfo.setStationElectricity(100.0);
        List<EquipmentStatsInfo> es = new ArrayList<>();
        statsInfo.setEquipmentStatsInfos(es);
        EquipmentStatsInfo e = new EquipmentStatsInfo();
        es.add(e);
        e.setEquipmentId("1000000001");
        e.setEquipmentElectricity(100.0);
        ArrayList<ConnectorStatsInfo> connectorStatsInfos = new ArrayList<>();
        e.setConnectorStatsInfos(connectorStatsInfos);
        ConnectorStatsInfo info1 = new ConnectorStatsInfo();
        connectorStatsInfos.add(info1);
        info1.setConnectorId("100000000101");
        info1.setConnectorElectricity(100.0);

        Result<QueryStationStatsResult> result = new Result<>(post);
        result.setRet(0);
        result.setMsg("请求成功");
        result.setData(postResult);
        return result;
    }
}
